package maosy.word.util

import java.io.FileInputStream

object FileType {

    private val typeMap = hashMapOf(
        "3c68746d6c20786d6c6e" to "htm",        //猎聘、智联简历
        "46726f6d3a3cd3c920cd" to "mht"         //51job 简历
    )

    /**
     * 获取文件类型
     */
    @Throws(Exception::class)
    fun fileType(path: String): String? {
        val fileInputStream = FileInputStream(path)
        val b = ByteArray(10)
        fileInputStream.read(b, 0, b.size)
        val fileCode = bytesToHexString(b)

        typeMap.keys.forEach { key ->
            if (key.toLowerCase().startsWith(fileCode.toLowerCase(),true) || fileCode.toLowerCase().startsWith(key.toLowerCase(),true)) {
                return typeMap[key]
            }
        }
        return null
    }

    private fun bytesToHexString(src: ByteArray): String {
        val sb = StringBuilder("")
        src.forEach { byte ->
            val v = byte.toInt() and 0xFF
            val hv = Integer.toHexString(v)
            if (hv.length < 2) {
                sb.append(0)
            }
            sb.append(hv)
        }
        return sb.toString()
    }


}